//
//  MusicList.swift
//  ShareMusic
//
//  Created by 胡岩 on 16/5/3.
//  Copyright © 2016年 胡岩. All rights reserved.
//

import UIKit

class MusicList: UIView, UITableViewDelegate, UITableViewDataSource, SMBTableViewDelegate {
    var currentNumberOfSongs = 0
    var startPoint:CGPoint?
    var button:UIButton?
    var lists:NSMutableArray = NSMutableArray.init(capacity: 0)
    var tableView:SMBTableView?
    var activityView:UIActivityIndicatorView?
    var clouse:Clouse?
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(CGRect.screenWidth(), 0, CGRect.screenWidth(), CGRect.screenHeight()))
        self.backgroundColor = UIColor.whiteColor()
        let window:UIWindow = UIApplication.sharedApplication().keyWindow!
        window.addSubview(self)
        
        self.button = UIButton.init(type: UIButtonType.Custom)
        self.button?.frame = CGRectMake(CGRect.screenWidth() - 30, CGRect.screenHeight() / 2.0 - 15, 30, 30)
        self.button?.setImage(UIImage.init(named: "向左"), forState: UIControlState.Normal)
        window.addSubview(self.button!)
        self.button?.addTarget(self, action: #selector(MusicList.tapButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.initView()
    }
    
    func tapButton(button:UIButton) {
        if self.frame.origin.x > 10 {
            self.open()
        } else {
            self.close()
        }
    }
    
    func initView() {
        self.tableView = SMBTableView.init(frame: CGRectMake(0, 20, CGRect.screenWidth(), CGRect.screenHeight() - 20), style: UITableViewStyle.Plain)
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.touchDelegate = self
        self.tableView?.separatorStyle = UITableViewCellSeparatorStyle.None
        self.addSubview(self.tableView!)
        self.tableView?.registerClass(SongsTableViewCell.self, forCellReuseIdentifier: "cell")
        self.activityView = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        self.activityView?.center = self.center
        self.addSubview(self.activityView!)
    }
    
    func tableViewTouchesBegan(tableView: UITableView, touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        self.startPoint = (touch as! UITouch).locationInView(self.superview?.superview)
    }
    
    func tableViewTouchesMoved(tableView: UITableView, touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        let movePoint = (touch as! UITouch).locationInView(self.superview?.superview)
        let x = movePoint.x - (self.startPoint?.x)! + self.frame.size.width / 2.0
        if x > self.frame.size.width / 2.0 {
            self.center = CGPointMake(x, self.frame.size.height / 2.0)
            self.button?.center = CGPointMake(x - 15 - self.frame.size.width / 2.0, CGRect.screenHeight() / 2.0 - 15)
        } else {
            self.open()
        }
    }
    
    func tableViewTouchesEnded(tableView: UITableView, touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        let endPoint = (touch as! UITouch).locationInView(self.superview?.superview)
        let previousPoint = (touch as! UITouch).previousLocationInView(self.superview)
        if endPoint.x - previousPoint.x > 0 {
            self.close()
        } else {
            self.open()
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:SongsTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! SongsTableViewCell
        cell.model = self.lists[indexPath.row] as! songModel
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        currentNumberOfSongs = indexPath.row
        self.playCurrentSong()
    }
    
    func playCurrentSong() {
        if self.lists.count > self.currentNumberOfSongs {
            let model:songModel = self.lists[self.currentNumberOfSongs] as! songModel
            SMMusicPlayer.shareInstance().play(model)
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.lists.count
    }
    
    class func shareInstance() -> MusicList {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: MusicList? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = MusicList.init(frame: CGRectMake(CGRect.screenWidth(), 0, CGRect.screenWidth(), CGRect.screenHeight()))
        }
        return Static.instance!
    }
    
    func reloadLists(array:NSArray) {
        self.lists.removeAllObjects()
        self.lists.addObjectsFromArray(array as [AnyObject])
        self.tableView?.reloadData()
    }
    
    func close() {
        UIView.animateWithDuration(0.4) {
            self.frame = CGRectMake(CGRect.screenWidth(), 0, CGRect.screenWidth(), CGRect.screenHeight())
            self.button?.frame = CGRectMake(CGRect.screenWidth() - 30, CGRect.screenHeight() / 2.0 - 15, 30, 30)
            self.button?.setImage(UIImage.init(named: "向左"), forState: UIControlState.Normal)
        }
        let window:UIWindow = UIApplication.sharedApplication().keyWindow!
        window.bringSubviewToFront(SMMusicPlayer.shareInstance())
        window.bringSubviewToFront(SMMusicPlayer.shareInstance().button!)
    }
    
    func open() {
        UIView.animateWithDuration(0.4) { 
            self.frame = CGRectMake(0, 0, CGRect.screenWidth(), CGRect.screenHeight())
            self.button?.frame = CGRectMake(0, CGRect.screenHeight() / 2.0 - 15, 30, 30)
            self.button?.setImage(UIImage.init(named: "向右"), forState: UIControlState.Normal)
        }
        let window:UIWindow = UIApplication.sharedApplication().keyWindow!
        window.bringSubviewToFront(self)
        window.bringSubviewToFront(button!)
        if self.clouse != nil {
            self.clouse!()
        }
    }
    
    func openClouse(clouse: ()->()){
        self.clouse = clouse
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
